package net.easyjava.api.controller;

import net.easyjava.api.constants.WebConstants;
import net.easyjava.base.manager.ArticleManager;
import net.easyjava.tools.BaseController;
import net.easyjava.tools.model.ModelBean;
import net.easyjava.tools.model.ModelConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by wenxiaoning on 15/12/18.
 */
@Controller
@RequestMapping("/api/article")
public class ArticleController extends BaseController {
    private  Logger logger = LoggerFactory.getLogger(this.getClass().getName());
    @Resource
    private ArticleManager articleManager;


    /**
     * 同一个浏览器用户第一次访问页面的时候返回一个随机用户
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/{type}")
    @ResponseBody
    public ModelBean article(
            @PathVariable String type,
            //查找一篇文章
            @RequestParam(required = false,defaultValue = "") String id,

            //获取列表使用
            @RequestParam(required = false,defaultValue = "1") int albumId,
            @RequestParam(required = false,defaultValue = "1") String pageNum,
            @RequestParam(required = false,defaultValue = "10") String pageSize,
            HttpServletRequest request, HttpServletResponse response) {
        ModelBean modelBean = null;
        String message = ModelConstants.MESSAGE_ERROR;
        try {
            if(WebConstants.ARTICLE_ONE.equals(type)){
                if("".equals(id)){
                    message = "id 不能为空";
                    throw new Exception();
                }
                modelBean = articleManager.findOne(request, response);
            }else if(WebConstants.ARTICLE_LIST.equals(type)){
                modelBean = articleManager.findList(request,response);
            }



        }catch (Exception e){
            logger.error(e.getMessage(),e.fillInStackTrace());
            modelBean = new ModelBean(message);
        }


        return model(modelBean, request, response);
    }
}
